

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:ycbl/common/EventBus.dart';
import 'package:ycbl/utils/PrefUtil.dart';
import 'package:ycbl/utils/log_util.dart';

import 'SearchItem.dart';

class SearchItemView extends StatefulWidget {
  final bool isHisSearch ;
  /// 是否允许删除
  const SearchItemView({this.isHisSearch});
  @override
  _SearchItemViewState createState() => _SearchItemViewState();
}

class _SearchItemViewState extends State<SearchItemView> {
  /// 历史搜索词
  List<dynamic> hisKeywords = new List() ;
  /// 推荐搜索词-大家都在搜
  List<dynamic> recommondKeywords = [
    '语文',
    '数学',
    '英语',
    '物理',
    '化学',
    '历史',
    '地理',
    '生物',
  ];
  /// 异步订阅管理
  StreamSubscription _searchDelSubscription;
  @override
  void initState(){
    super.initState();
    _getHisKeywords();
    /// 监听删除事件
    _searchDelSubscription = eventBus.on<DelSearchKeyEvent>().listen((event){
      this._delHisKeywords(event.keywords);
    });
  }

  /// 之所以定义为async，因为后续需要改造为从SharedPreferences本地获取搜索历史
  Future<void> _getHisKeywords() async {
    hisKeywords = PrefUtil.getStringList("search_history_Keywords");
    LogUtil.e("_getHisKeywords hisKeywords  ${hisKeywords.toString()}");
    return hisKeywords;
  }

  /// 之所以定义为async，因为后续需要改造为从SharedPreferences本地获删除
  Future<void> _delHisKeywords(String keywords) async {
    if(this.hisKeywords.isNotEmpty && this.hisKeywords.contains(keywords)){
      this.hisKeywords.remove(keywords);
      /// 刷新状态
      setState(() {

      });
    }
  }
  @override
  Widget build(BuildContext context) {
    _getHisKeywords();
    List<dynamic> items = widget.isHisSearch ? hisKeywords : recommondKeywords;
    return (items!=null&&items.length>0)?Padding(padding: EdgeInsets.all(10),
        child: Container(
          child: Wrap(
            spacing: 10,
            children: items.map((item) {
              /// 构造Item widget
              return SearchItem(title: item, isHisSearch: widget.isHisSearch,);
            }).toList(),
          ),
        )
    ):Center(child: Text("暂无内容"),);
  }
  @override
  void dispose(){
    super.dispose();
    /// 取消监听，节省系统资源
    _searchDelSubscription.cancel();
  }
}